import { defineStore } from 'pinia'
import { getUserLogin, getCartListData, getDeleteGoods } from '@/api/shopCart'

// 创建仓库
export const useCartStore = defineStore(`cart`, {
  // 数据初始化
  state() {
    return {
      token: localStorage.getItem(`token`) || '',
      cartInfoList: [] as any[],
      goodspriceAll: 0
    }
  },
  // 逻辑的处理
  actions: {
    // 计算总价
    async priceAll(price: any) {
      this.goodspriceAll = price
    },
    // 创建调用登录接口函数
    async userLoginInfo() {
      try {
        const result = await getUserLogin({ phone: 13700000000, password: 111111 })
        this.token = result.data.token
        localStorage.setItem(`token`, this.token)
      } catch (err) {
        return Promise.reject(`failed`)
      }
    },
    // 创建调用获取购物车商品列表的接口函数
    async CartListData() {
      try {
        const result = await getCartListData()
        this.cartInfoList = result.data[0].cartInfoList
      } catch (err) {
        return Promise.reject(`failed`)
      }
    },
    // 创建删除单个商品的接口函数
    async DeleteGoods(id: number) {
      await getDeleteGoods(id)
    }
  }
})
